/**
 * 任务管理 列表页
 *
 * 作者 ganjun
 * 日期 2024-11-18 10:06:38
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'dropdown','table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        dropdown = layui.dropdown,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-task'),
        $query = $view.find('#query'),
        $taskType = $view.find('#taskType'),
        $status = $view.find('#status'),
        $searchForm = $view.find('#task-table-form'),
        tableIns;

    form.verify(validate);
    form.render();
    febs.initDictItemSelect($taskType, 'TASK_TYPE', null, null);
    febs.initDictItemSelect($status, 'TASK_STATUS', null, null);
    renderDate('#pauseDate', 'yyyy-MM-dd');
    renderDate('#completeDate', 'yyyy-MM-dd');


    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'taskTable',
            url: ctx + 'task/list',
            where: getQueryParams(),
            height: getTableHeight(),
            autoSort: true,
            skin: '',
            cols: [[
                {field: 'createdTime', title: '', width: 100,sort:true,hide:true,order:'desc'},
                {field: 'projectCode', title: '项目编号', width: 120,sort:true},
                {field: 'projectName', title: '项目名称', width: 150,sort:true},
                {field: 'taskCode', title: '任务编号', width: 140,sort:true},
                {field: 'taskTypeName', title: '任务类型', width: 100},
                {field: 'statusName', title: '任务状态', width: 100},
                {field: 'shipnames', title: '船模', width: 200,sort:true},
                {field: 'oarsnames', title: '桨模', width: 120,sort:true},
                {field: 'attachnames', title: '附体', width: 120,sort:true},
                {field: 'planStartdate', title: '计划开始时间', width: 120, templet: function (d){
                         var endtime=' '+d.planStarttime;
                         if(d.planStarttime==null||d.planStarttime==undefined){
                             endtime='';
                         }
                         if(d.planStartdate==null||d.planStartdate==undefined){
                             return ''+endtime;
                         }else{
                             return  layui.util.toDateString(d.planStartdate, "yyyy-MM-dd")+endtime;
                         }
                    }},
                {field: 'planEnddate', title: '计划结束时间', width: 120,templet:function (d){
                    var endtime=' '+d.planEndtime;
                      if(d.planEndtime==null||d.planEndtime==undefined){
                          endtime='';
                      }
                      if(d.planEnddate==null||d.planEnddate==undefined){
                          return ''+endtime;
                      }else {
                          return  layui.util.toDateString(d.planEnddate, "yyyy-MM-dd HH:mm")+endtime;
                      }
                    }},
                {field: 'actuallyStartdate', title: '实际开始时间', width: 120,templet:function (d){
                      if(d.actuallyStartdate==null||d.actuallyStartdate==undefined){
                          return '';
                      }else {
                          return  layui.util.toDateString(d.actuallyStartdate, "yyyy-MM-dd HH:mm");
                      }
                    }},
                {field: 'actuallyEnddate', title: '实际结束时间', width: 120,templet:function (d){
                     if(d.actuallyEnddate==null||d.actuallyEnddate==undefined){
                         return  '';
                     }else {
                         return  layui.util.toDateString(d.actuallyEnddate, "yyyy-MM-dd HH:mm");
                     }
                    }},
                {title: '操作', width: 180, align: 'left', templet: function (d) {
                   var str = '<div class="layui-clear-space">';
                      if(d.status!=2 && d.status!=6) {
                          str += ' <a lay-event="edit" shiro:hasPermission="task:edit">' +
                              '<em class="layui-icon febs-edit-area febs-blue">&#xe83f;</em>修改</a>' +
                              '<a lay-event="del" shiro:hasPermission="task:delete">' +
                              '<em class="layui-icon febs-edit-area febs-red">&#xe7f9;</em>删除</a>';
                      }
                      var  buttonNum=0;
                      if(febs.include(permissionSet, "task:detail")){
                          buttonNum++;
                      }
                      if((d.status==5||d.status==8)&&febs.include(permissionSet, "progress:complete")){
                          buttonNum++;
                      }

                      if((d.taskType==1)&&(d.status==5)&&febs.include(permissionSet, "progress:pause")){
                            buttonNum++;
                        }
                        if(buttonNum>1){
                            str += '<a class="layui-btn layui-btn-xs" lay-event="more">' +
                                '更多<i class="layui-icon layui-icon-down"></i></a></div>';
                            return str;
                        }else {
                            if((d.status==5||d.status==8)){
                              str+='<a lay-event="complete" shiro:hasPermission="progress:complete"><em class="layui-icon febs-edit-area febs-pink">&#xe7a5;</em>完成</a>';
                            }
                            if((d.taskType==1&&(d.status==5))){
                                str+='<a lay-event="pause" shiro:hasPermission="progress:pause"><em class="layui-icon febs-edit-area febs-yellow">&#xe894;</em>暂停</a>';
                            }
                            str+='<a  lay-event="detail" shiro:hasPermission="task:detail"><em   class="layui-icon febs-edit-area febs-red">&#xe7b3;</em>详情</a>';
                            return  str;
                        }
                  }},
            ]],
            toolbar: '#taskToolbar',
            defaultToolbar: [],
            done: function (res, curr, count) {
                 if(!febs.include(permissionSet, "task:add")){
                    $('div.layui-table-tool').css('display','none');
                }else {
                     $('div.layui-table-tool').css('display','block');
                 }
            }
        });
    }

        table.on('sort(taskTable)', function (obj) {
            tableIns.reload({
                initSort: obj,
                where: $.extend(getQueryParams(), {
                    field: obj.field,
                    order: obj.type
                }),
                autoSort: true
            });
        });

    function renderDate(element, format) {
        laydate.render({
            elem: element,
            type: 'date',
            format: format,
            btns: ['now', 'confirm'],
            trigger: 'click',
            isInitValue: true
        });
    }



        function reloadPage(curr) {
            var _curr = $view.find(".layui-laypage-em").next().html();
            if (!!curr) {
                _curr = curr;
            }
            tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
        }

        $query.on('click', function () {
            reloadPage(1);
        });


    table.on('toolbar(taskTable)', function (obj) {
        parent.layui.febs.navigate("/task/add",true);
    });

        table.on('tool(taskTable)', function (obj) {
            var data = obj.data;
            var   layEvent = obj.event;
            if (layEvent === 'del') {
                febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                    deleteIds(data.taskCode);
                });
            }

            if (layEvent === 'edit') {
                parent.layui.febs.navigate('/task/update/'+ data.taskCode,true);
            }


            if (layEvent === 'complete') {
                 openComplete(data);
            }
            if (layEvent === 'pause') {
                openPause(data);
            }

            if (layEvent === 'detail') {
                parent.layui.febs.navigate("/task/detail/" + data.taskCode + "?type=detail",true);
            }



            if (layEvent === 'more') {
                // 更多 - 下拉菜单
                button = [];
                if (data.status==5||data.status==8) {
                    var complete = {
                        id: 'complete',
                        title: '完成',
                        templet:'<a><em class="layui-icon febs-edit-area febs-pink">&#xe7a5;</em>完成</a>'
                    }
                    if (febs.include(permissionSet, "progress:complete")) {
                        button.push(complete);
                    }
                }

                if(data.taskType==1&&(data.status==5)) {
                    var pause = {
                        id: 'pause',
                        title: '暂停',
                        templet:'<a><em class="layui-icon febs-edit-area febs-yellow">&#xe894;</em>暂停</a>'
                    }
                    if (febs.include(permissionSet, "progress:pause")) {
                        button.push(pause);
                    }
                }

                var detail = {
                    id: 'detail',
                    title: '详情',
                    templet:'<a><em class="layui-icon febs-edit-area febs-red">&#xe7b3;</em>详情</a>'
                }
                if (febs.include(permissionSet, "task:detail")) {
                    button.push(detail);
                }

                dropdown.render({
                    elem: this, // 触发事件的 DOM 对象
                    show: true, // 外部事件触发即显示
                    data: button,
                    click: function (menudata) {
                        if (menudata.id === 'complete') {
                            openComplete(data);
                        } else if (menudata.id === 'pause') {
                            openPause(data);
                        } else if (menudata.id === 'detail') {
                            parent.layui.febs.navigate("/task/detail/" + data.taskCode + "?type=detail",true);
                        }
                    },
                    align: 'right', // 右对齐弹出
                    style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                });
            }
        });


    form.on('submit(pause-submit)', function (data) {
        data=data.field;
        data.taskCode=data.pauseTaskCode;
        data.planEnddate =data.pauseDate;
        data.planEndtime=data.pauseTime;
        febs.postArray(ctx + 'progress/pause' ,data,  function () {
        });
        $query.click();
    })

     //完成分排期任务和非排期任务
    form.on('submit(complete-submit)', function (data) {
        data=data.field;
        data.taskCode=data.completeTaskCode;
        data.planEnddate=data.completeDate;
        data.planEndtime=data.completeTime;
        febs.postArray(ctx + 'progress/complete' ,data,  function () {
        });
        $query.click();
    })

    form.on('submit(nonSchedulesubmit)', function (data) {
        data=data.field;
        data.taskCode=data.nonSchdeduleTaskCode;
        data.planStartdate=data.nonScheduleStartDate;
        data.planStarttime=data.nonScheduleStartTime;
        data.planEnddate=data.nonScheduleEndDate;
        data.planEndtime=data.nonScheduleEndtime;
         if (data.planStartdate > data.planEnddate ) {
                febs.alert.warn('开始时间不能大于结束时间');
              return false;
            }
        febs.postArray(ctx + 'task/nonScheduleComplete' ,data,  function () {
        });
        $query.click();
    })

        function getQueryParams() {
            return {
                taskType: $searchForm.find('select[name="taskType"]').find("option:selected").val() .trim(),
                projectName: $searchForm.find('input[name="projectName"]').val() == null ? "" : $searchForm.find('input[name="projectName"]').val().trim(),
                status: $status.val() == null ? "" : $status.val().trim(),
                invalidate_ie_cache: new Date()
            };
        }

        function deleteIds(ids) {
            febs.get(ctx + 'task/delete/' + ids, null, function () {
                febs.alert.success('删除数据成功');
                $query.trigger('click');
            })
        }

        function getTableHeight() {
            return commonJS.calcTableHeight();
        }

        $(window).resize(function () {
            tableIns.reload({height: getTableHeight()});
        });

       function  openPause(data){
           layer.open({
               type: 1,
               title: '暂停任务',
               offset: ['300px', '400px'],
               area:  ['370px', '243px'] ,
               shade:0,
               btn: ['提交'],
               closeBtn:1,
               content: $('#pauseDialog'),
               yes: function (layero, index) {
                   $('#pauseSubmit').trigger('click');
               }, cancle(layero,index) {
                   layer.closeAll();
               },success(){
                   $("#pauseTaskCode").val(data.taskCode);
                   renderDate('#pauseDate', 'yyyy-MM-dd');
                   form.render();
                   layui.form.render('select');
                   handleResetModalPos(['#pauseTime']);
               }
           });
       }

       function   openComplete(data){
           if(data.taskType==1){
               layer.open({
                   type: 1,
                   title: '完成任务',
                   offset: ['300px', '400px'],
                   area:  ['370px', '175px'] ,
                   shade:0,
                   btn: ['提交'],
                   closeBtn: 1,
                   content: $('#completeDialog'),
                   yes: function (layero, index) {
                       $('#completeSubmit').trigger('click');
                   }, cancle() {
                       layer.closeAll();
                   },success(){
                       $("#completeTaskCode").val(data.taskCode);
                       renderDate('#completeDate', 'yyyy-MM-dd');
                       form.render();
                       layui.form.render('select')
                       handleResetModalPos(['#completeTime']);
                   },close(){
                       layer.closeAll();
                   }
               });
           }else {
               layer.open({
                   type: 1,
                   title: '完成任务',
                   offset: ['280px', '420px'],
                   area:  ['370px', '225px'] ,
                   shade:0,
                   btn: ['提交'],
                   closeBtn: 1,
                   content: $('#nonSchdeduleDialog'),
                   yes: function (layero, index) {
                       $('#nonSchedulesubmit').trigger('click');
                   }, cancle() {
                       layer.closeAll();
                   },success(){
                       $("#nonSchdeduleTaskCode").val(data.taskCode);
                     //  renderMinDate('#nonScheduleStartDate','#nonScheduleEndDate', 'yyyy-MM-dd');
                       renderDate('#nonScheduleStartDate','yyyy-MM-dd');
                       renderDate('#nonScheduleEndDate','yyyy-MM-dd');
                       form.render();
                       layui.form.render('select');
                       handleResetModalPos(['#nonScheduleStartTime', '#nonScheduleEndtime']);
                   }
               });
           }
       }


            /**
             * 根据当前点击的选择框动态设置展开位置
             * 调用位置：重新加载table数据时。
             * @param elClass 选择器类名
             * **/
            function handleResetModalPos(elClass) {
                if (!Array.isArray(elClass)) {
                    elClass = [elClass]
                }
                elClass.forEach(function (name) {
                    $(`${name} + .layui-form-select .layui-anim-upbit`).css({
                        width: '240px',
                        minHeight: '200px',
                        minWidth: 'unset',
                        left: 'unset',
                        top: 'unset',
                        position: 'fixed',
                    })
                    $(`${name} + .layui-form-select`).click(function () {
                        var clickElementOffset = $(this).offset();
                        var targetTop = clickElementOffset.top + $(this).outerHeight();
                        var cont = $(this).find('.layui-anim-upbit')
                        // 如果出现滚动条
                       $(this).parents('.layui-layer-content').scrollLeft(0);
                        cont.css('top', targetTop)
                    })
                })
            }




    }

)